package com.wtcrazy.utils;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/*
 * JWT工具类
 * */
public class JwtUtil {
    private static long time = 60 * 60 * 24 * 3;//设置过期时间,单位s【3天】
    private static String secret = "abcdfghiabcdfghiabcdfghiabcdfghi";//密钥32位随机字符串

    //创建token
    public static String createToken(String id) {
        Date now = new Date();
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                //载荷Payload【eg:856dd57f4b084d4c8249d13e32380d7c】
                .claim("userId", id)//真正封装的信息
                .setSubject("加密userId")//设置主题,类似于key
                .setIssuedAt(now)//现在生效【签发时间】iat
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * time))//过期时间【】exp
                .signWith(SignatureAlgorithm.HS256, secret)//签名算法
                .compact();
        System.out.println(jwtToken);
        return jwtToken;
    }

    //解析token
    public static void parseToken(String token) {
// token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiI4NTZkZDU3ZjRiMDg0ZDRjODI0OWQxM2UzMjM4MGQ3YyIsInN1YiI6IuWKoOWvhnVzZXJJZCIsImlhdCI6MTY5MTMxMTk5NSwiZXhwIjoxNjkxMzE1NTk1fQ._Zi872hRiiI0C1bvAjahsLWbT7LdCu7IPoh_TeRysJM";
        JwtParser jwtParser = Jwts.parser();
        //类似map集合
        Jws<Claims> claimsJws = jwtParser
                .setSigningKey(secret)
                .parseClaimsJws(token);
        //获取Jws对象的数据
        Claims claims = claimsJws.getBody();//用户保存的信息
        System.out.println("userId====" + claims.get("userId"));
    }

    //验证token是否过期
    public static Integer checkToken(String token) {
        if (token == null || token.equals("")) {
            System.out.println("缺失Token");
            return 0;//过期
        }
        //Boolean result = Jwts.parser().isSigned(token);//这个不靠谱
        try {
            Jws<Claims> claimsJws = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token);
            System.out.println("Token正确");
            return 1;
        } catch (Exception e) {
            System.out.println("Token异常或过期");
            return -1;
        }
    }
}
